package com.vanke.kotlin_mvp

import android.content.Intent
import android.os.Bundle
import android.support.v4.view.GravityCompat
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.AppCompatActivity
import android.view.MenuItem
import com.vanke.kotlin_mvp.data.Injection
import com.vanke.kotlin_mvp.main.TasksFilterType
import com.vanke.kotlin_mvp.statistics.StatisticsActivity
import com.vanke.kotlin_mvp.util.ActivityUtils
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    private lateinit var drawerLayout: DrawerLayout

    private val CURRENT_FILTERING_KEY = "CURRENT_FILTERING_KEY"

    private lateinit var mainPresenter: MainPresenter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //Set up the toolbar
        setSupportActionBar(toolbar)
        supportActionBar?.let {
            it.setHomeAsUpIndicator(R.drawable.ic_menu)
            it.setDisplayHomeAsUpEnabled(true)
        }

        //set up navigation drawer
        drawerLayout = draw_layout.apply {
            setStatusBarBackground(R.color.colorPrimaryDark)
        }

        nav_view.setNavigationItemSelectedListener { item: MenuItem ->
            if (item.itemId == R.id.statistics_navigation_menu_item) {
                val intent = Intent(this@MainActivity, StatisticsActivity::class.java)
                startActivity(intent)
            }
            item.isChecked = true
            drawerLayout.closeDrawers()
            true
        }

        val mainFragment = supportFragmentManager.findFragmentById(R.id.contentFrame)
                as MainFragment? ?: MainFragment.newInstance().also {
            ActivityUtils.addFragmentToActivity(supportFragmentManager, it, R.id.contentFrame)
        }

         mainPresenter = MainPresenter(Injection.provideTasksRepository(applicationContext), mainFragment).apply {
            if (savedInstanceState != null) {
                currentFiltering = savedInstanceState.getSerializable(CURRENT_FILTERING_KEY)
                        as TasksFilterType
            }
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        outState.putSerializable(CURRENT_FILTERING_KEY,mainPresenter.currentFiltering)
        super.onSaveInstanceState(outState)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home)
            drawerLayout.openDrawer(GravityCompat.START)
        return super.onOptionsItemSelected(item)
    }
}
